#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../include/log_file.h"
#define FILENAME "./log/log.log"

FILE *file;
char *buffs = NULL;
int flag = 0;

void init_file(){
    file = fopen(FILENAME, "a+");
}

void close_file(){
    fclose(file);
    if(buffs != NULL){
        free(buffs);
    }
}

char* get_local_time(){
    char *my_date = (char*) malloc (100*sizeof(char));
    time_t rawtime;
    struct tm *timeinfo;
    time(&rawtime);
    timeinfo = localtime( &rawtime);
    sprintf(my_date,"%04d-%02d-%02d %02d:%02d:%02d",
    (timeinfo->tm_year + 1900), timeinfo->tm_mon, timeinfo->tm_mday,\
    timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
    return my_date;
}


void write_buff_log(char* type, char* value, int size){
    if(flag == 0 || buffs == NULL){
        buffs = (char*) malloc (size * 20 * sizeof(char));
    }
    char* buff = (char*) malloc (size * sizeof(char));
    char* my_date = get_local_time();
    sprintf(buff, "\t%s : %s : %s\n", type, my_date, value);
    strcat(buffs, buff);
    free(my_date);
    free(buff);
    buff = NULL;
    flag = 1;
}

void write_to_log(char* type, char* user, char* value){
    init_file();
    char buff[1024];
    char* my_date = get_local_time();
    sprintf(buff, "%s : %s : %s : %s\n", type, my_date, user, value);
    fputs(buff, file);
    fflush(file);
    free(my_date);
    if(flag == 1){
        fputs(buffs, file);
        fflush(file);
        buffs[0] = '\0';
        free(buffs);
        buffs = NULL;
    }
    flag = 0;
    close_file();
}

